package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.BaseCategory1Mapper;
import com.atguigu.tingshu.album.mapper.BaseCategory2Mapper;
import com.atguigu.tingshu.album.mapper.BaseCategory3Mapper;
import com.atguigu.tingshu.album.mapper.BaseCategoryViewMapper;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.model.album.BaseCategory1;
import com.atguigu.tingshu.model.album.BaseCategory2;
import com.atguigu.tingshu.model.album.BaseCategory3;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;


    /**
     * 查询所有分类（1、2、3级分类）在一级分类下包含二级，二级分类下包含三级
     *
     * @return
     */
    @Override
    @GuiGuCache(prefix = "allCategoryList")
    public List<JSONObject> getBaseCategoryList() {
        //1.查询所有分类视图记录 419条记录
        List<BaseCategoryView> allCategoryViewList = baseCategoryViewMapper.selectList(null);
        List<JSONObject> allJSONObjectList = new ArrayList<>();

        //2.处理一级分类
        //2.1 对所有分类视图集合进行分组得到Map：根据一级分类ID分组 Map中Key:分组1级ID Val:当前一级分类下所有视图记录
        Map<Long, List<BaseCategoryView>> category1ListMap = allCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));        //2.2 遍历一级分类Map 没遍历一次就处理一个1级分类对象
        if (CollectionUtil.isNotEmpty(category1ListMap)) {
            //2.2 遍历一级分类Map 每遍历一次处理一个一级分类
            for (Map.Entry<Long, List<BaseCategoryView>> entry1 : category1ListMap.entrySet()) {
                //2.3 构建1级分类JSON对象，封装1级ID跟名称，子分类列表
                Long category1Id = entry1.getKey();
                String category1Name = entry1.getValue().get(0).getCategory1Name();
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("categoryId", category1Id);
                jsonObject1.put("categoryName", category1Name);

                //3.处理二级分类列表，将二级分类集合加入到一级分类对象中“categoryChild”
                //3.1 将当前1级分类集合 按照二级分类ID进行分组
                Map<Long, List<BaseCategoryView>> category2ListMap = entry1.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
                //3.2 遍历二级分类Map集合,每遍历一次处理一个二级分类
                List<JSONObject> category2JsonObjectList = new ArrayList<>();
                for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2ListMap.entrySet()) {
                    //3.3 构建2级分类JSON对象，封装2级ID跟名称，子分类列表
                    Long category2Id = entry2.getKey();
                    String category2Name = entry2.getValue().get(0).getCategory2Name();
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("categoryId", category2Id);
                    jsonObject2.put("categoryName", category2Name);
                    category2JsonObjectList.add(jsonObject2);
                    //4.处理三级分类类别，将三级分类集合加入到二级分类对象中“categoryChild”
                    List<JSONObject> category3JsonObjectList = new ArrayList<>();
                    for (BaseCategoryView baseCategoryView : entry2.getValue()) {
                        JSONObject jsonObject3 = new JSONObject();
                        jsonObject3.put("categoryId", baseCategoryView.getCategory3Id());
                        jsonObject3.put("categoryName", baseCategoryView.getCategory3Name());
                        category3JsonObjectList.add(jsonObject3);
                    }
                    jsonObject2.put("categoryChild", category3JsonObjectList);
                }

                jsonObject1.put("categoryChild", category2JsonObjectList);
                allJSONObjectList.add(jsonObject1);
            }
        }
        //5.返回所有一级分类集合
        return allJSONObjectList;
    }


    /**
     * 根据三级分类ID查询分类视图对象
     *
     * @param category3Id
     * @return
     */
    @Override
    @GuiGuCache(prefix = "categoryView:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    /**
     * 首页中展示指定1级分类下前7个三级分类集合
     *
     * @param category1Id:一级分类ID
     * @return
     */
    @Override
    @GuiGuCache(prefix = "topBaseCategory3:")
    public List<BaseCategory3> getTopBaseCategory3(Long category1Id) {
        //1.根据一级分类ID查询二级分类集合
        LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id, category1Id);
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);

        //2.处理二级分类集合获取二级分类ID集合
        if (CollectionUtil.isNotEmpty(baseCategory2List)) {
            List<Long> baseCategory2IdList = baseCategory2List.stream().map(BaseCategory2::getId).collect(Collectors.toList());
            //3.根据二级分类ID集合查询三级分类列表，查询前7个
            LambdaQueryWrapper<BaseCategory3> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(BaseCategory3::getCategory2Id, baseCategory2IdList);
            queryWrapper.last("limit 7");
            return baseCategory3Mapper.selectList(queryWrapper);
        }

        return null;
    }

    /**
     * 查询指定一级分类下包含二级分类列表（二级分类下三级分类列表
     *
     * @param category1Id 1级分类ID
     * @return
     */
    @Override
    @GuiGuCache(prefix = "baseCategoryListByCategory1:")
    public JSONObject getBaseCategoryListByCategory1Id(Long category1Id) {
        //1.根据1分类ID查询分类视图-得到一级分类列表
        LambdaQueryWrapper<BaseCategoryView> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseCategoryView::getCategory1Id, category1Id);
        List<BaseCategoryView> category1List = baseCategoryViewMapper.selectList(queryWrapper);

        //2.处理一级分类下二级分类，根据一级分类集合中二级分类ID进行分组
        if (CollectionUtil.isNotEmpty(category1List)) {
            //2.1 构建一级分类对象
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("categoryId", category1List.get(0).getCategory1Id());
            jsonObject1.put("categoryName", category1List.get(0).getCategory1Name());

            Map<Long, List<BaseCategoryView>> category2ListMap = category1List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            List<JSONObject> jsonObject2List = new ArrayList<>();
            for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2ListMap.entrySet()) {
                Long category2Id = entry2.getKey();
                String category2Name = entry2.getValue().get(0).getCategory2Name();
                //2.2 构建二级分类JSON对象
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("categoryId", category2Id);
                jsonObject2.put("categoryName", category2Name);
                jsonObject2List.add(jsonObject2);
                //3.处理二级分类下三级分类
                List<JSONObject> jsonObject3List = new ArrayList<>();
                for (BaseCategoryView baseCategoryView : entry2.getValue()) {
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("categoryId", baseCategoryView.getCategory3Id());
                    jsonObject3.put("categoryName", baseCategoryView.getCategory3Name());
                    jsonObject3List.add(jsonObject3);
                }
                //4.将三级分类集合放入二级分类对象中"categoryChild"属性中
                jsonObject2.put("categoryChild", jsonObject3List);
            }
            //2.3 将二级分类集合放入一级分类对象中"categoryChild"属性中
            jsonObject1.put("categoryChild", jsonObject2List);
            return jsonObject1;
        }
        return null;
    }
}
